﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace MailChimp4Umbraco.Businesslogic.ChimpAPI
{
    public class MailChimpCommunicator
    {
        /// <summary>
        /// WebClient used for sending API requests to MailChimp
        /// </summary>
        private WebClient _webClient { get; set; }

        /// <summary>
        /// MailChimp API key
        /// </summary>
        private string _APIKey { get; set; }

        /// <summary>
        /// Create new instance of MailChimpCommunicator to call the MailChimp API
        /// </summary>
        /// <param name="mailChimpAPIKey">API key</param>
        public MailChimpCommunicator(string mailChimpAPIKey)
        {
            _webClient = new WebClient();
            _APIKey = mailChimpAPIKey;
        }

        /// <summary>
        /// Add subscriber to your MailChimp account
        /// </summary>
        /// <param name="emailAddress">Receiver email address</param>
        /// <param name="userIpAddress">IP address of the user. It's important that this is the real IP address of the user</param>
        /// <returns></returns>
        public MailChimpResponse AddSubscriber(string mailChimpListId, string emailAddress, string userIpAddress, string firstName, string lastName)
        {
            // Build API call URL
            string dataCenter = String.Empty;
            if (!String.IsNullOrEmpty(_APIKey))
            {
                dataCenter = _APIKey.Substring(_APIKey.Length - 3, 3) + ".";
            }

            string APIUrl = string.Format("http://{6}api.mailchimp.com/1.2/?method=listSubscribe&apikey={0}&id={5}&email_address={1}&merge_vars[EMAIL]={1}&merge_vars[FNAME]={2}&merge_vars[LNAME]={3}&merge_vars[OPTINIP]={4}&email_type=html&update_existing=0&replace_interests=1&output=xml", _APIKey, emailAddress, firstName, lastName, userIpAddress, mailChimpListId, dataCenter);

            #region Call API
            try
            {
                byte[] data = _webClient.DownloadData(APIUrl);
                return new MailChimpResponse(ASCIIEncoding.ASCII.GetString(data));

            } catch (Exception)
            {
                // If we end up here, the MailChimp API URL is not valid
                return new MailChimpResponse(string.Empty);
            }

            #endregion
        }


        /// <summary>
        /// Remove subscriber from your MailChimp account
        /// </summary>
        /// <param name="emailAddress">Receiver email address that is to be removed</param>
        /// <returns></returns>
        public MailChimpResponse UnSubscribe(string mailChimpListId, string emailAddress)
        {
            // Build API call URL
            string APIUrl = string.Format("http://api.mailchimp.com/1.2/?method=listUnsubscribe&apikey={0}&id={2}&email_address={1}&delete_member=1&send_goodbye=1&send_notify=0&output=xml", _APIKey, emailAddress, mailChimpListId);

            #region Call API
            try
            {
                byte[] data = _webClient.DownloadData(APIUrl);
                return new MailChimpResponse(ASCIIEncoding.ASCII.GetString(data));

            }
            catch (Exception)
            {
                // If we end up here, the MailChimp API URL is not valid
                return new MailChimpResponse(string.Empty);
            }

            #endregion
        }

    }
}
